#include<iostream>
using namespace std;
#include<vector>
class Solution {
public:
    int m, n, dx[4] = { -1,1,0,0 }, dy[4] = { 0,0,-1,1 };
    vector<vector<int>> dp;
    int dfs(vector<vector<int>>& matrix, int x1, int y1) {
        if (dp[x1][y1] > 1)
            return dp[x1][y1];
        for (int i = 0; i < 4; ++i) {
            int x = dx[i] + x1, y = dy[i] + y1;
            if (x >= 0 && x < m && y >= 0 && y<n && matrix[x][y]>matrix[x1][y1])
                dp[x1][y1] = max(dp[x1][y1], 1 + dfs(matrix, x, y));
        }
        return dp[x1][y1];
    }
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        m = matrix.size(), n = matrix[0].size();
        int ans = 0;
        dp.resize(m, vector<int>(n, 1));
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                ans = max(ans, dfs(matrix, i, j));
        return ans;
    }
};